package com.toman.ui.work.workshop;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.zhouwei.library.CustomPopWindow;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.PlanEntity;
import com.toman.JavaBean.SendworkorderEntity;
import com.toman.JavaBean.StaticsCount;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DialogBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class PlanActivity extends ToolBarActivity {
    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.tv_select2)
    TextView tvSelect2;
    @BindView(R.id.iv_select2)
    ImageView ivSelect2;
    @BindView(R.id.rl_select2)
    RelativeLayout rlSelect2;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.cb_muti)
    CheckBox cbMuti;
    @BindView(R.id.btn_muti)
    Button btnMuti;
    @BindView(R.id.rl_muti)
    RelativeLayout rlMuti;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    int page = 2;
    private List<PlanEntity> list = new ArrayList<>();
    Dialog dialog;
    private String auditStatus="0";
    private String planStatus="";
    private String status="0";
    CommonAdapter<PlanEntity> adapter;
    private CustomPopWindow mCustomPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.PLAN.name);
        initView();
//        initList();
    }

    private void initList() {
        for (int i = 0; i < 10; i++) {
            PlanEntity bean = new PlanEntity();
            list.add(bean);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();

        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))){
            p_id=(getIntent().getStringExtra("etSearch"));
            setStatus(getIntent().getStringExtra("status"));
        }else {

            customer(1, 1, etSearch.getText().toString());
        }
    }


    private void initView() {
        baseEnum=BaseEnum.PLAN;
        etSearch.setHint("计划单号/序号/品号/品名");
        ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.CHECK), rlMuti);
        initAdapter();
        cbMuti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setCheckStatus(b);
                }


                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<PlanEntity> beanlist = adapter.getDatas();
                PlanEntity  bean=beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putString("status", status);
                IntentUtils.startActivity(PlanActivity.this, PlanInfActivity.class, bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
//        mEmptyWrapper = new EmptyWrapper(adapter);
//        mEmptyWrapper.setEmptyView(R.layout.empty_view);
        lv.setAdapter(adapter);
//        mEmptyWrapper.notifyDataSetChanged();

//        LinearLayoutManager manager = new LinearLayoutManager(this);
//        lv.setLayoutManager(manager);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        lv.setLayoutManager(linearLayoutManager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
//                content1=content2=content3=content4=null;
                p_id=null;

                    dialog = null;
                    dialogList.clear();
                    page = 2;
                    customer(1, 1, etSearch.getText().toString().trim());


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_add, menu);
//        MenuItem menuItem = menu.findItem(R.id.menu_scan);
        MenuItem menuItem = menu.findItem(R.id.menu_add);

        if (!PermissonUtils.contains(this, BaseEnum.PLAN.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
                        Bundle bundle = new Bundle();
                        bundle.putString("id", departmentId);
                        bundle.putString("status", "0");
                        IntentUtils.startActivity(PlanActivity.this, PlanAddActivity.class, bundle);
                        break;



                }
                return false;
            }
        });

        return true;
    }
    private void initAdapter() {
        adapter = new CommonAdapter<PlanEntity>(this, R.layout.item_workshop_plan, list) {
            @Override
            protected void convert(ViewHolder holder, PlanEntity item, final int position) {
                holder.setText(R.id.tv_time,item.getCreateTime());
                holder.setText(R.id.tv_code,item.getPlanNum());
                holder.setText(R.id.tv_no,item.getProductEntity().getProductName());
                holder.setText(R.id.tv_dep,item.getDepartmentEntity().getDepartmentName());
                holder.setText(R.id.tv_beltline,item.getOperationArtlineEntity().getArtlineName());
                holder.setText(R.id.tv_need,item.getDemandCount()+"");
                holder.setText(R.id.tv_dispatching,item.getPlanCompleteCount().getDispatchCount()+"");
                holder.setText(R.id.tv_finish,item.getPlanCompleteCount().getCompletedCount()+"");
                holder.getView(R.id.btn_del).setOnClickListener(v -> deleteDialog(item));
                holder.getView(R.id.btn_look).setOnClickListener(v -> jump(item));

                if (item.getAuditStatus().equals("0")){
  CheckBox checkBox=  holder.getView(R.id.cb_status);
  checkBox.setChecked(item.getCheckStatus());
                    checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> item.setCheckStatus(isChecked));
                    holder.getView(R.id.cb_status).setVisibility(View.VISIBLE);
    holder.getView(R.id.btn_del).setVisibility(View.VISIBLE);
    holder.getView(R.id.btn_check).setVisibility(View.VISIBLE);
                    ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.CHECK), holder.getView(R.id.btn_check));
                    ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.DELETE), holder.getView(R.id.btn_del));
                    holder.getView(R.id.btn_check).setOnClickListener(v -> mutiCheckDialog(item.getId() + ""));
//    权限
    holder.getView(R.id.btn_more).setVisibility(View.GONE);
    holder.getView(R.id.btn_pg).setVisibility(View.GONE);
    holder.getView(R.id.btn_finish).setVisibility(View.GONE);
    holder.getView(R.id.btn_look).setVisibility(View.GONE);

}

else if (item.getPlanStatus().equals("0")){
                    holder.getView(R.id.cb_status).setVisibility(View.GONE);
                    holder.getView(R.id.btn_finish).setOnClickListener(v -> completeConfirm(item));

                    holder.getView(R.id.btn_del).setVisibility(View.GONE);
    holder.getView(R.id.btn_check).setVisibility(View.GONE);
    holder.getView(R.id.btn_more).setVisibility(View.VISIBLE);
    if (position+1==list.size()){
        holder.getView(R.id.btn_more).setOnClickListener(v -> showPopMenu((Button) v, item,true));
    }
    else {
        holder.getView(R.id.btn_more).setOnClickListener(v -> showPopMenu((Button) v, item,false));

    }
    holder.getView(R.id.btn_pg).setVisibility(View.VISIBLE);

                    holder.getView(R.id.btn_pg).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("bean", item);
                            IntentUtils.startActivity(PlanActivity.this, PlanDispatchingActivity.class, bundle);
                        }
                    });
    holder.getView(R.id.btn_finish).setVisibility(View.VISIBLE);
                    holder.getView(R.id.btn_look).setVisibility(View.GONE);


}
      else  if (item.getPlanStatus().equals("2")){
                    holder.getView(R.id.cb_status).setVisibility(View.GONE);
    holder.getView(R.id.btn_del).setVisibility(View.VISIBLE);

                    holder.getView(R.id.btn_check).setVisibility(View.GONE);
    holder.getView(R.id.btn_more).setVisibility(View.GONE);
    holder.getView(R.id.btn_pg).setVisibility(View.GONE);
    holder.getView(R.id.btn_finish).setVisibility(View.GONE);
    holder.getView(R.id.btn_look).setVisibility(View.VISIBLE);
                    holder.getView(R.id.btn_look).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            jump(item);
                        }
                    });
                }
//                权限管理
                ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.FINISH), holder.getView(R.id.btn_finish));
                ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.DELETE), holder.getView(R.id.btn_del));
                ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.DISPATCHING), holder.getView(R.id.btn_pg));
                if (!PermissonUtils.contains(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.CHECK))) {
                    holder.getView(R.id.cb_status).setVisibility(View.GONE);
                }
            }


        };
    }


    public void completeDialog(final PlanEntity bean, List<SendworkorderEntity> list ) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化
String message="";
        StringBuilder stringBuilder=new StringBuilder();

if (list.size()!=0){
    stringBuilder.append("有未结束的派工单(");
    for (SendworkorderEntity entity : list) {
        if (stringBuilder.length()==9){
            stringBuilder.append(entity.getSendworkCode());
        }
        else {
            stringBuilder.append(",").append(entity.getSendworkCode());

        }
    }
    stringBuilder.append("),是否完工?");
message=stringBuilder.toString();
}


        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确定要完成车间计划？")
                .setMessage(message)
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        complete(bean);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }


    private void completeConfirm(PlanEntity bean) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .get(NewBaseUrl.workshop_plan_complete_confirm + bean.getId())
                .headers("token", token)
//                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "完工车间计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {

                            List<SendworkorderEntity> jsonArray = new ArrayList<SendworkorderEntity>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("list"), SendworkorderEntity.class));

                            completeDialog(bean,jsonArray);


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    private void complete(PlanEntity bean) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_plan_complete + bean.getId())
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "完工车间计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            customer(1, 1, "");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
    public void deleteDialog(final PlanEntity bean) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确定要删除车间计划？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        delete(bean);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }
    private void delete(PlanEntity bean) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", bean.getId() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_plan_dekete + bean.getId())
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "删除车间计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            customer(1, 1, "");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }
    public void customer(Integer page, final Integer type, String search) {
        if (dialog!=null){
            dialog.dismiss();
        }



        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.workshop_plan_list)
//                .params("companyId", companyId)
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num)
                .params("page", page.toString())
                .params("auditStatus", auditStatus)
                .params("id",p_id)
                .params("planStatus", planStatus);

for (DialogBean bean: dialogList){
  params.params(bean.getSubmitName(),bean.getResult());
}


                params.execute(new StringLoadingCallback(this,mPullToRefreshScrollView,search) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "车间计划列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            List<PlanEntity> jsonArray = new ArrayList<PlanEntity>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), PlanEntity.class));
                            list.addAll(jsonArray);
                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
                            });
                            tvSelect0.setText("待审核(" + count.getCount0() + ")");
                            tvSelect1.setText("进行中(" + count.getCount1() + ")");
                            tvSelect2.setText("已结束(" + count.getCount2() + ")");
                            setCbMuti();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }
    private void setStatus(String status){
        this.status=status;
        switch (status){
            case "0":
                auditStatus="0";
                planStatus="";
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                tvSelect2.setTextColor(getResources().getColor(R.color.black33));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect2.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, etSearch.getText().toString());
                ViewUtil.permission(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.CHECK), rlMuti);

                break;
            case "1":
                auditStatus="";
                planStatus="0";
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect2.setTextColor(getResources().getColor(R.color.black33));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect2.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));


                customer(1, 1, etSearch.getText().toString());
                break;
            case "2":
                auditStatus="";
                planStatus="2";
                tvSelect2.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect2.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));

                customer(1, 1, etSearch.getText().toString());


                break;

        }
    }

    private void setCbMuti(){
        cbMuti.setChecked(false);

        switch (status){
            case "0":
                btnMuti.setText("一键审核");
                if (PermissonUtils.contains(this, baseEnum.has(PermEnum.CHECK))&&list.size()!=0){
                    rlMuti.setVisibility(View.VISIBLE);
                }
                else {
                    rlMuti.setVisibility(View.GONE);
                }
                break;

            default:
                rlMuti.setVisibility(View.GONE);
        }

    }

    public void setSelect(String select) {
        switch (select) {
            case "0":
                setStatus("0");
                break;
            case "1":
                setStatus("1");
                break;
            case "2":
                setStatus("1");
                break;
            case "4":
                setStatus("2");
                break;
        }
    }

    private void showPopMenu(Button button,PlanEntity entity,boolean isBottom){
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu,null);
        //处理popWindow 显示内容
        handleLogic(contentView,entity);
        //创建并显示popWindow
        mCustomPopWindow= new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create();
                if (isBottom){
                    mCustomPopWindow.showAsDropDown(button,0,-160);

                }
                else {
                    mCustomPopWindow .showAsDropDown(button,0,20);

                }


    }

    private void handleLogic(View contentView,PlanEntity entity){
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mCustomPopWindow!=null){
                    mCustomPopWindow.dissmiss();
                }
                String showContent = "";
                switch (v.getId()){
                    case R.id.menu1:
                        jump(entity);
                        break;
                    case R.id.menu2:
                        deleteDialog(entity);
                        break;
                    case R.id.menu3:
                        showContent = "点击 Item菜单3";
                        break;

                }
            }
        };
        contentView.findViewById(R.id.menu1).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2).setOnClickListener(listener);
        contentView.findViewById(R.id.menu3).setOnClickListener(listener);
    }

    private void jump(PlanEntity entity) {
        Bundle bundle = new Bundle();
        bundle.putString("planId", entity.getId() + "");
        IntentUtils.startActivity(PlanActivity.this, DispatchingActivity.class, bundle);
    }

    public void mutiCheckDialog(final String ids) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认审核选中的车间计划吗？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        check(ids);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }
    public void mutiCheckDialogNew(final String ids) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认一键审核选中的车间计划吗？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        check(ids);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }
    private void check( String ids) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", ids );

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_plan_verify +ids)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "审核车间计划: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            customer(1, 1, "");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private String getMutiCheck() {
        StringBuilder stringBuffer = new StringBuilder();

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCheckStatus()) {
                if (stringBuffer.length() <= 0) {
                    stringBuffer.append(list.get(i).getId());
                } else {
                    stringBuffer.append(",").append(list.get(i).getId());
                }
            }
        }
        if (stringBuffer.length() <= 0) {
            return null;
        } else {
            return stringBuffer.toString();
        }

    }
    @OnClick({R.id.tv_select,R.id.rl_select0, R.id.rl_select1, R.id.rl_select2, R.id.cb_muti, R.id.btn_muti})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
            case R.id.rl_select2:
                setStatus("2");
                break;
            case R.id.btn_muti:
                if (getMutiCheck()==null){
                    ToastUtil.makeText(getApplicationContext(),"请至少选中一个选项");
                }
                else {
                    mutiCheckDialogNew(getMutiCheck());
                }
                break;
            case R.id.tv_select:
                showDialog();
                break;
        }
    }

    public void showDialog() {
        if (dialog == null) {
            dialogList.clear();
            dialogList.add( new DialogBean("departmentId","部门名称", 1, BaseNetUtil.base(this, NetworkEnum.DEP, mCompanyId)));
            dialogList.add( new DialogBean("productId","品名", 1, BaseNetUtil.base(this, NetworkEnum.PRODUCT, mCompanyId)));
            dialogList.add( new DialogBean("artlineId","工艺路线名称", 1, BaseNetUtil.base(this, NetworkEnum.ARTLINE, mCompanyId)));
            dialogList.add( new DialogBean("customer","客户"));


            dialog = DialogUtils.selectNewDialog(this, dialogList, new ActionCallback() {
                @Override
                public void run() {
                    customer(1, 1, "");
                    dialog.dismiss();

                }
            });
            dialog.show();
        } else {
            dialog.show();
        }
    }
}
